﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.UI;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.ComponentModel;
using Lilium.Web.Mvc.AjaxControlToolkit;

namespace Lilium.Web.Mvc.MicrosoftAjax
{
	[JavaScriptReference(Constants.AjaxLibraryName, Constants.CultureInfoResourceName, LoadOrder = 0)]
	[JavaScriptReference(Constants.AjaxLibraryName, "MicrosoftAjax.js", LoadOrder = 1)]
	[JavaScriptReference(Constants.AjaxLibraryName, "MicrosoftMvcAjax.js", LoadOrder = 2)]
	public abstract class MicrosoftAjaxBehavior: IScriptDescriptor
	{
		#region public string ScriptType

		private readonly string m_ScriptType;

		public string ScriptType { [DebuggerNonUserCodeAttribute] get { return m_ScriptType; } }

		#endregion

		#region public string ElementID

		private readonly string m_ElementID;

		public string ElementID { [DebuggerNonUserCodeAttribute] get { return m_ElementID; } }

		#endregion

		#region IScriptDescriptor Members

		public IEnumerable<IScriptResourceReference> GetResourceReferences()
		{
			return ScriptResourceReflectionHelper.GetResourceReferences(this.GetType());
		}

		public virtual void RegisterScript(AjaxHelper ajaxHelper)
		{
			var scriptResourceData = ScriptResourceData.EnsureResourceData(ajaxHelper);
			scriptResourceData.RegisterClientScript(ajaxHelper, this);
		}

		public void RenderResources(AjaxHelper ajaxHelper)
		{
			var scriptResourceData = ScriptResourceData.EnsureResourceData(ajaxHelper);

			foreach (var resourceReference in GetResourceReferences())
				scriptResourceData.RenderScriptResourceReference(ajaxHelper, resourceReference);
		}

		public abstract void RenderScript(AjaxHelper ajaxHelper);

		#endregion

		protected MicrosoftAjaxBehavior(string scriptType, string elementID)
		{
			if (string.IsNullOrEmpty(scriptType))
				throw new ArgumentNullOrEmptyException("scriptType");
			if (string.IsNullOrEmpty(elementID))
				throw new ArgumentNullOrEmptyException("elementID");

			m_ElementID = elementID;
			m_ScriptType = scriptType;
		}
	}
}